package com.syqc.monitor.ui.simplemonitor

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import autodispose2.autoDispose
import com.syqc.comlib.UserConstant
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.ArrayUtil
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.entity.GpsDetail
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.PublishSubject

/**
 *@Author Jasper
 *@Time   2021/3/16
 *@Desc   todo
 */
class SimpleMonitorViewModel : AutoDisposeViewModel() {


    var teamId = ""
    var isClear = false
    private val allCas = ArrayList<GpsDetail>()
    private var mCarsHandle: UpdateHandle? = null
    private val mCarsHandleThread: HandlerThread by lazy { HandlerThread("mListHandleThread") }
    private val carsSub by lazy { PublishSubject.create<MutableList<GpsDetail>>() }

    fun carsObserver(): Observable<MutableList<GpsDetail>> = carsSub.hide()

    init {
        initThread()

    }

    /**
     * 初始化线程
     */
    private fun initThread() {
        mCarsHandleThread.start()
        mCarsHandle = UpdateHandle(mCarsHandleThread.looper)
    }

    /**
     * 停止线程
     */
    private fun stopThread() {
        mCarsHandle?.removeCallbacksAndMessages(null)
        mCarsHandleThread.quit()
    }

    /**
     * 排序方式
     */
    var sortByType: String
        get() = CacheMMKV.decodeString("sort_type_s", "carPlate")
        set(value) {
            CacheMMKV.encode("sort_type_s", value)
            refreshData()
        }

    /**
     * 刷新数据
     */
    private fun refreshData() {
        if (allCas.size > 0) {
            val msg = Message.obtain()
            msg.obj = allCas
            msg.what = 1
            mCarsHandle?.sendMessage(msg)
        }
    }


    /**
     * 查询定位数据
     */
    fun getCarsLocation() {
        if (isClear || UserConstant.current_car_num > 300 && teamId.isEmpty()) {
            toast(R.string.toast_choose_team)
            return
        }
        toastLoading(true)
        ServiceHelper.getRepository().getGpsRInfo(teamId, "").autoDispose(this)
            .subscribe({
                toastLoading(false)
                val msg = Message.obtain()
                msg.obj = it
                msg.what = 0
                mCarsHandle?.sendMessage(msg)
            }, error)
    }

    /**
     * 通过车辆Id获取定位信息
     */
    private fun getLocationsByCarIds(carIds: String) {
        ServiceHelper.getRepository().getGpsRInfo("", carIds).autoDispose(this)
            .subscribe({
                toastLoading(false)
                val msg = Message.obtain()
                msg.obj = it
                msg.what = 0
                mCarsHandle?.sendMessage(msg)
            }, error)
    }

    private var allData: MutableList<GpsDetail> = mutableListOf()

    internal inner class UpdateHandle(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                var locations = msg.obj as MutableList<GpsDetail>
                locations = ArrayUtil.sortBy(
                    locations,
                    sortByType,
                    true
                ) as MutableList<GpsDetail>
                allData.clear()
                allData.addAll(locations);
                carsSub.onNext(locations)
            } else if (msg.what == 1) {
                val locations = msg.obj as MutableList<GpsDetail>
                handleRefresh(locations)
            }
        }
    }

    fun search(key: String, isPlate: Boolean) {
        val upKey = key.uppercase()
        val data = allData.filter {
            if (isPlate) {
                it.carPlate.uppercase().contains(upKey)
            } else {
                it.carName.uppercase().contains(upKey)
            }
        } as MutableList<GpsDetail>?
        carsSub.onNext(data ?: mutableListOf())
    }

    fun setAllData() {
        carsSub.onNext(allData)
    }

    /**
     * 刷新
     */
    fun refresh(locations: MutableList<GpsDetail>) {
        if (locations.isEmpty()) return
        val msg = Message.obtain()
        msg.obj = locations
        msg.what = 1
        mCarsHandle?.sendMessage(msg)
    }

    private val stringBuilder = StringBuilder()
    private fun handleRefresh(locations: MutableList<GpsDetail>) {
        toastLoading(true)
        stringBuilder.setLength(0)
        for (location in locations) {
            stringBuilder.append(location.carId)
            stringBuilder.append(",")
        }
        if (stringBuilder.length > 1) {
            stringBuilder.deleteAt(stringBuilder.lastIndex)
            val carIds = stringBuilder.toString()
            getLocationsByCarIds(carIds)
        } else {
            toastLoading(false)
        }

    }



    override fun onCleared() {
        super.onCleared()
        stopThread()
    }
}

